//TCP通信的客户端（无多进程）
#include<stdio.h>
#include<arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>



// add(0x00101010)  0x0001  0x0001
//OS - K  把我们的代码当做一个整体进行保存
//class  进程
//操作选项
// 你的代码
int main() {


    //1创建socket
    int cfd = socket(AF_INET,SOCK_STREAM,0);
    if(cfd == -1) {
        perror("socket");
        exit(-1);
    }
    //2与服务端连接
    struct sockaddr_in saddr;
    saddr.sin_family = AF_INET;
    saddr.sin_port = htons(9999);
    inet_pton(AF_INET,"127.0.0.1",&saddr.sin_addr.s_addr);
    int ret = connect(cfd,(struct sockaddr *)&saddr,sizeof(saddr));
    if(ret == -1) {
        perror("connect");
        exit(-1);
    }

    //3通信
    char revbuf[1024];
    int i = 0;
    while(1) {
        //发送信息给服务端
        sprintf(revbuf,"hello ! I am Client：%d\n",i++);
        //sprintf(revbuf, "data : %d\n", i++);
        write(cfd,revbuf,strlen(revbuf)+1);//加1是为了把 字符串终止符发送过去 以免产生bug(该bug跟字符串长短相关)
        //i++;
        //接收服务端信息
        int len = read(cfd,revbuf,sizeof(revbuf));
        if(len == -1) {
            perror("read");
            exit(-1);
        } else if(len > 0) {
            printf("Client have recieved :%s\n",revbuf);
        } else if(len == 0) {
            printf("Sever have closed..");
            break;
        }
    }


    //4关闭
    close(cfd);

    return 0;
}

